import React from "react"
import { connect } from 'react-redux'
import { Button, Form, Input, Switch, Icon, Select, Popconfirm, message, Popover} from 'antd'
import {SelectDepOrPerson} from 'components/index';
import SelectDepWithChildren from "components/template/select-depment-with-children/select-depment-with-children"
import ReportDistributionService from "containers/report-distribution/report-distribution.service";
import { messages } from "share/common";
import "styles/report-distribution/report-distribution.scss"
import fullImg from 'images/fullVisible.png';
import SelectByBtn from "components/template/select-by-btn";
import Chooser from "components/chooser";
import ResizeTable from 'components/resize-table'
const FormItem = Form.Item;
const Option = Select.Option;

class ReportDistributionMaintain extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      loading: false,
      data: [],
      reportDetail:[],
      newCopyReportDetail:[],
      isNew: true,
      pagination: {
        total: 0,
        current: 1
      },
      page: 0,
      pageSize: 10,
      columns: [
        {title: messages("common.sequence"), dataIndex: 'index', width: '10%'},    //序号
        {title: messages('report-distribution.key14'/*工号*/), dataIndex: "employeeID", render: value => {
            return <Popover placement="topLeft" content={value}>{value}</Popover>
          }},  //工号
        {title: messages('report-distribution.key15'/*姓名*/), dataIndex: "fullName", render: value => {
            return <Popover placement="topLeft" content={value}>{value}</Popover>
          }}, //姓名
        {title: messages('report-distribution.key16'/*公司名称*/), dataIndex: "companyName", render: value => {
            return <Popover placement="topLeft" content={value}>{value}</Popover>
          }}, //公司名称
        {title: messages('report-distribution.key17'/*部门*/), dataIndex: "departmentName", render: value => {
            return <Popover placement="topLeft" content={value}>{value}</Popover>
          }},    //部门
        {title: messages('report-distribution.key18'/*职务*/), dataIndex: "title", render: value => {
            return <Popover placement="topLeft" content={value}>{value}</Popover>
          }},   //职务
        {title: messages('common.operation'), dataIndex: 'userOID', width: '10%', render: value => {
            return (
              <Popconfirm onConfirm={() => this.handleDelete(value)} title={messages('common.confirm.delete')}>
                <a onClick={e => {e.preventDefault();e.stopPropagation()}}>{messages('common.delete')}</a>
              </Popconfirm>
            )
          }}
      ],
      dataAreaOptions:[],
      copyReportCorporation:[],
      SetOfBookList:[],
      checkedSetOfBookList:[],
      checkedDep:[],//包含下级部门
      checkedParDep:[],//不包含下级部门
      checkedCompany:[],
      employeeOperation: [
        {operate: "", result: []} //operate：add添加操作 del删除操作；result：对应操作数据
      ],//用来记录对报表副本人员列表的操作，由于新建报表保存后才能拿到reportLineOID(保存前拿的是暂存的上次操作报表的reportLineOID)，所以无法在保存之前对人员列表操作，先暂存操作，保存报表时再处理
      reportLineOID:""
    };
  }

  componentWillMount() {
    this.getVisibleScopeList(); //获取报表分配中报表可见范围属性列表
    this.getCopyReportSetOfBookList();//获取 报表副本 账套列表
  }

  componentWillReceiveProps(nextProps) {
    this.setState({loading: true});
    // props每变一次就会调用一次，所以赋值如果写一起会被空值覆盖
    if (!nextProps.params || nextProps.params === this.props.params) {
      this.setState({loading: false});
      return false;
    }else{
      if (nextProps.params.reportDetail) {
        this.setState({
          isNew: nextProps.params.isNew,
          pagination: nextProps.params.pagination,
          reportDetail:nextProps.params.reportDetail,
          reportLineOID: nextProps.params.reportLineOID,
          //清空已选项  取消编辑后 点击另一条分配详情 清空可见数据范围的已选项 但要保留在本条内切换可见范围的已选项
          copyReportCorporation:[],
          checkedSetOfBookList:[],
          checkedDep:[],
          checkedParDep:[],
          checkedCompany:[],
          //清空对人员列表操作的记录
          employeeOperation:  [
            {operate: "", result: []}
          ]//operate：add添加操作 del删除操作；result：对应操作数据
        }, () => {
          if(!nextProps.params.isNew && nextProps.params.reportDetail.dataArea === "5"){
            this.getCopyReportCorporation();  //获取 单条 报表副本 已选法人列表
          }
          if(!nextProps.params.isNew && nextProps.params.reportDetail.dataArea === "8"){
            this.getCheckedSetOfBookList();  //获取 单条 报表副本 已选账套列表
          }
          if(!nextProps.params.isNew && nextProps.params.reportDetail.dataArea === "4"){//不包含下级部门
            this.getcheckedParDepList(); //获取 单条 报表副本 已选部门列表
          }
          if(!nextProps.params.isNew && nextProps.params.reportDetail.dataArea === "6"){//包含下级部门
            this.getCheckedDepList(); //获取 单条 报表副本 已选部门列表
          }
          if(!nextProps.params.isNew && nextProps.params.reportDetail.dataArea === "9"){
            this.getCheckedCompanyList();  //获取 单条 报表副本 已选公司列表
          }
          if(!nextProps.params.isNew && nextProps.params.reportDetail.isPublic === "N") {
            this.getList();  //获取 报表副本 分配人员列表
          }
        });
        this.setState({loading: false});
      }
      if (nextProps.params.newCopyReportDetail) {
        this.setState({
          loading: false,
          //清空编辑时已分配人员
          data:[],
          isNew: nextProps.params.isNew,
          pagination: nextProps.params.pagination,
          reportLineOID: nextProps.params.reportLineOID,
          newCopyReportDetail:nextProps.params.newCopyReportDetail,
          //清空已选项  取消编辑后 点击另一条分配详情 清空可见数据范围的已选项 但要保留在本条内切换可见范围的已选项
          copyReportCorporation:[],
          checkedSetOfBookList:[],
          checkedDep:[],
          checkedParDep:[],
          checkedCompany:[],
          //清空对人员列表操作的记录
          employeeOperation:  [
            {operate: "", result: []}
          ],//operate：add添加操作 del删除操作；result：对应操作数据
        });
      }
    }
  }

  //获取当前 报表副本 分配人员列表
  getList = () => {
    this.setState({loading: true});
    let { page, pageSize, reportLineOID} = this.state;
    ReportDistributionService.getDistributionPeopleList(page, pageSize,reportLineOID).then((response) => {
      response.data.map((item,index) => {
        item.index = index + page * pageSize + 1;
        item.key = item.userOID;
        item.departmentName = item.department.name;
      });
      this.setState({
        loading: false,
        data: response.data,
        pagination: {
          total: Number(response.headers['x-total-count']) ? Number(response.headers['x-total-count']) : 0,
          onChange: this.onChangePager,
          current: this.state.page + 1
        }
      });
    });
  };



  //获取报表分配中报表可见范围属性列表
  getVisibleScopeList = () => {
    let language= this.props.language;
    this.setState({loading: true});
    ReportDistributionService.getVisibleScopeList(language).then((response) => {
      this.setState({
        loading: false,
        dataAreaOptions: response.data
      });
    });
  }

  //获取 报表副本 账套列表
  getCopyReportSetOfBookList = () => {
    this.setState({loading: true});
    ReportDistributionService.getCopyReportSetOfBookList().then((response) => {
      response.data.map((item) => {
        item.key = item.objOID;
        item.setOfBooksName = item.name;
      });
      this.setState({
        loading: false,
        SetOfBookList: response.data
      });
    });
  }
  //获取 单条 报表副本 已选法人列表
  getCopyReportCorporation = () => {
    this.setState({loading: true});
    let { reportLineOID} = this.state;
    ReportDistributionService.getCopyReportCorporation(reportLineOID,3).then((response) => {
      response.data.map((item) => {
        item.key = item.objOID;
        item.companyName = item.name;
      });
      this.setState({
        loading: false,
        copyReportCorporation: response.data
      });
    });
  }

  //获取 单条 报表副本 已选账套列表
  getCheckedSetOfBookList = () => {
    this.setState({loading: true});
    let { reportLineOID} = this.state;
    ReportDistributionService.getCopyReportCorporation(reportLineOID,4).then((response) => {
      response.data.map((item) => {
        item.setOfBooksId = item.objID;
        item.setOfBooksName = item.name;
      });
      this.setState({
        loading: false,
        checkedSetOfBookList: response.data
      });
    });
  }

  //获取 单条 报表副本 已选包含下级部门列表
  getCheckedDepList = () => {
    this.setState({loading: true});
    let { reportLineOID} = this.state;
    ReportDistributionService.getCopyReportCorporation(reportLineOID,2).then((response) => {
      response.data.map((item) => {
        item.departmentOID = item.objOID;
        item.key = item.objOID;
        item.label = item.name;
      });
      this.setState({
        loading: false,
        checkedDep: response.data
      });
    });
  };

  //获取 单条 报表副本 已选包含下级部门列表
  getcheckedParDepList = () => {
    this.setState({loading: true});
    let { reportLineOID} = this.state;
    ReportDistributionService.getCopyReportCorporation(reportLineOID,2).then((response) => {
      response.data.map((item) => {
        item.departmentOID = item.objOID;
        item.key = item.objOID;
        item.label = item.name;
      });
      this.setState({
        loading: false,
        checkedParDep: response.data
      });
    });
  }

  //获取 单条 报表副本 已选公司列表
  getCheckedCompanyList = () => {
    this.setState({loading: true});
    let { reportLineOID} = this.state;
    ReportDistributionService.getCopyReportCorporation(reportLineOID,5).then((response) => {
      response.data.map((item) => {
        item.companyOID = item.objOID;
      });
      this.setState({
        loading: false,
        checkedCompany: response.data
      });
    });
  }


  updateCopyReport = (e) => {
    e.preventDefault();
    this.setState({loading: true});
    const { copyReportCorporation, newCopyReportDetail, checkedDep, checkedParDep, checkedSetOfBookList, checkedCompany, reportDetail, isNew, employeeOperation } = this.state;
    let copyReportDetails = {
      copyName: this.props.form.getFieldValue('copyName'),
      copyComments: this.props.form.getFieldValue('copyComments'),
      employeeListChanged: false,
      createdDate: new Date(),
      dataArea: this.props.form.getFieldValue('dataArea'),
      isPublic: this.props.form.getFieldValue('isPublic') ? "Y" : "N",
      isCopy: "Y",
      status:this.props.form.getFieldValue('status') ? "open" : "closed",
      reportLineOID: this.state.reportLineOID,
      // reportHeadDTO: {},
      reportObjDTOs:[]
    }
    if(this.props.form.getFieldValue('dataArea') === "5"){
      copyReportCorporation.map((item) => {
        copyReportDetails.reportObjDTOs.push({
          objName:item.companyName,
          objOID:item.key,
          objType:"3"
        });
      })
    }
    if(this.props.form.getFieldValue('dataArea') === "8"){
      checkedSetOfBookList.map((item) => {
        copyReportDetails.reportObjDTOs.push({
          objName:item.setOfBooksName,
          objID:item.setOfBooksId,
          objType:"4"
        });
      })
    }
    if(this.props.form.getFieldValue('dataArea') === "9"){
      checkedCompany.map((item) => {
        copyReportDetails.reportObjDTOs.push({
          objName:item.name,
          objOID:item.companyOID,
          objType:"5"
        });
      })
    }
    if(this.props.form.getFieldValue('dataArea') === "4"){
      checkedParDep.map((item) => {
        copyReportDetails.reportObjDTOs.push({
          objName:item.label,
          objOID:item.key,
          objType:"2"
        });
      })
    }
    if(this.props.form.getFieldValue('dataArea') === "6"){
      checkedDep.map((item) => {
        copyReportDetails.reportObjDTOs.push({
          objName:item.label,
          objOID:item.key,
          objType:"2"
        });
      })
    }
    if(isNew){
      Object.assign(copyReportDetails,{reportHeadDTO: {reportHeadOID:newCopyReportDetail.reportHeadOID}});
      copyReportDetails.reportLineOID = null;
      ReportDistributionService.saveCopyReport(copyReportDetails).then((response) => {
        const reportLineOID = response.data.reportLineOID;
        employeeOperation.map((item) => {
          if(item.operate === "add"){
            let reportObjDTOs = [];
            item.result.map(item => {
              let reportObjDTO ={
                objOID:item.userOID,
                objType: "1"
              };
              reportObjDTOs.push(reportObjDTO)
            });
            let params = {reportLineOID, reportObjDTOs};
            ReportDistributionService.saveEmployeeToCopyReport(params).then().catch( e => {
              message.error(e.response.data.message);
            });
          }
          if(item.operate === "del"){
            let removeObjDTOs =[{
              objOID:item.result,
              objType: "1"
            }];
            let params = { reportLineOID, removeObjDTOs};
            ReportDistributionService.deleteEmployeesOfCopyReport(params).then().catch(e => {
              message.error(e.response.data.message);
            });
          }
        });
        this.setState({
          loading: false
        });
        this.props.form.resetFields();
        this.props.close(true);
        message.success(messages('common.operate.success'));
      }).catch((e) => {
        let errorMessage = e.response.data.message;
        if(e.response.data.validationErrors){
          errorMessage = e.response.data.validationErrors[0].message;
        }
        message.error(errorMessage);
        ReportDistributionService.deleteAllotReportDetail(reportLineOID).then(() => {
          //不清空刚刚填写的数据
        })
      });
    }else{
      Object.assign(copyReportDetails,{reportHeadDTO: reportDetail.reportHeadDTO});
      ReportDistributionService.updateCopyReport(copyReportDetails).then((response) => {
        const reportLineOID = response.data.reportLineOID;
        employeeOperation.map((item) => {
          if(item.operate === "add"){
            let reportObjDTOs = [];
            item.result.map(item => {
              let reportObjDTO ={
                objOID:item.userOID,
                objType: "1"
              };
              reportObjDTOs.push(reportObjDTO)
            });
            let params = {reportLineOID, reportObjDTOs};
            ReportDistributionService.saveEmployeeToCopyReport(params).then().catch(e => {
              message.error(e.response.data.message);
            });
          }
          if(item.operate === "del"){
            let removeObjDTOs =[{
              objOID:item.result,
              objType: "1"
            }];
            let params = { reportLineOID, removeObjDTOs};
            ReportDistributionService.deleteEmployeesOfCopyReport(params).then().catch(e => {
              message.error(e.response.data.message);
            });
          }
        });
        this.setState({
          loading: false
        });
        this.props.form.resetFields();
        this.props.close(true);
        message.success(messages('common.operate.success'));
      }).catch(e => {
        let errorMessage = e.response.data.message;
        if(e.response.data.validationErrors){
          errorMessage = e.response.data.validationErrors[0].message;
        }
        message.error(errorMessage);
      });
    }

  }

  onCancel = () => {
    this.props.form.resetFields();
    this.setState({
      data: [],
      reportDetail:[],
      newCopyReportDetail:[],
      isNew: true,
      copyReportCorporation:[],
      checkedSetOfBookList:[],
      checkedDep:[],
      checkedParDep:[],
      reportLineOID:""
    });
    this.props.close();
  };

  //翻页
  onChangePager = (page) => {
    if(page - 1 !== this.state.page)
      this.setState({page: page - 1,}, this.getList);
  };

  addDepCallback = (result) => {
    this.setState({
      checkedDep: result
    });
  };

  addParDepCallback = (result) => {
    this.setState({
      checkedParDep: result
    });
  }

  getCorporation = (result) => {
    this.setState({
      copyReportCorporation: result
    });
  }

  getSetOfBookList = (result) => {
    this.setState({
      checkedSetOfBookList: result
    });
  }

  getCompanyList = (result) => {
    this.setState({
      checkedCompany: result
    });
  }

  //删除员工列表,暂存删除操作及数据
  handleDelete = (OID) => {
    let { data,employeeOperation } = this.state;
    this.setState({loading: true});
    data.splice(data.findIndex(item => item.key === OID), 1);
    employeeOperation.push({operate: "del", result: OID});
    this.setState({
      data: data,
      loading: false,
      employeeOperation: employeeOperation
    });
  };

  //过滤重复数据后添加员工
  addStaffsByOrg = (result) => {
    //这一部分打算先做数据暂存最后保存再调接口处理数据，最后取消了这个方案，这里注释一下以免日后再改回来
    //果然需要改回来
    let { data,employeeOperation } = this.state;
    let unSelectedData = [];
    this.setState({loading: true});
    result.map((item) => {
      let flag = 1;
      item.index = data.length + 1;
      item.key = item.userOID;
      //筛选出重复数据
      for(let dataitem of data){
        if(dataitem.userOID === item.userOID){
          flag = 0;
        }
      }
      if(flag){
        data.push(item);
        unSelectedData.push(item);
      }
    });
    employeeOperation.push({operate: "add", result: unSelectedData});
    this.setState({
      data: data,
      loading: false,
      employeeOperation: employeeOperation
    });
  };

  addStaffsByCon = (result) => {
    //这一部分打算先做数据暂存最后保存再调接口处理数据，最后取消了这个方案，这里注释一下以免日后再改回来
    let { data,employeeOperation } = this.state;
    let unSelectedData = [];
    this.setState({loading: true});
    result.map((item) => {
      let flag = 1;
      item.value.index = data.length + 1;
      item.value.key = item.value.userOID;
      //筛选出重复数据
      for(let dataitem of data){
        if(dataitem.userOID === item.value.userOID){
          flag = 0;
        }
      }
      if(flag){
        data.push(item.value);
        unSelectedData.push(item.value);
      }
    });
    employeeOperation.push({operate: "add", result: unSelectedData});
    this.setState({
      data: data,
      loading: false,
      employeeOperation: employeeOperation
    });
  };

  handleClose = (removedTag) => {
    const checkedDep = this.state.checkedDep.filter(tag => tag.departmentOID !== removedTag);
    this.setState({ checkedDep });
  };

  renderDataArea() {
    switch(this.props.form.getFieldValue('dataArea')){
      case "6": //指定部门 包括下级部门
      {
        const { checkedDep } = this.state;
        return(
          <SelectDepWithChildren onConfirm={this.addDepCallback}
                                 isIncludeChildren={true}
                                 title={messages('report-distribution.key19'/*指定部门（包含下级部门）*/)}
                                 defaultValue={checkedDep}
          />
        );
        break;
      }
      case "4": //指定部门 不包括下级部门
      {
        const { checkedParDep } = this.state;
        return(
          <SelectDepWithChildren onConfirm={this.addParDepCallback}
                                 isIncludeChildren={false}
                                 title={messages('report-distribution.key20'/*指定部门（不包含下级部门）*/)}
                                 defaultValue={checkedParDep}
          />
        );
        break;
      }
      case "5": //指定法人
      {
        let { copyReportCorporation } = this.state;
        return(
          <Chooser type={"corporation_entity_all"}
                   valueKey={"key"}
                   labelKey={"companyName"}
                   value={copyReportCorporation}
                   onChange={this.getCorporation}
          />
        );
        break;
      }
      case "8": //指定账套
      {
        const { checkedSetOfBookList} = this.state;
        return(
          <Chooser type={"select_set_of_books"}
                   valueKey={"setOfBooksId"}
                   labelKey={"setOfBooksName"}
                   value={checkedSetOfBookList}
                   onChange={this.getSetOfBookList}
          />
        );
        break;
      }
      case "9": //指定公司
      {
        const { checkedCompany } = this.state;
        return(
          <Chooser type={"enabled_company"}
                   valueKey={"companyOID"}
                   labelKey={"name"}
                   value={checkedCompany}
                   onChange={this.getCompanyList}
          />
        );
        break;
      }
    }
  };
  renderFullVisible() {
    return(
      <div className={"img-center"}>
        <img src={fullImg} />
        <p>{messages('report-distribution.key21'/*该报表数据所有公司人员可见*/)}</p>
      </div>
    )
  };
  renderNonFullVisible() {
    const { data, pagination, columns, loading } = this.state;
    return(
      <div>
        <div className="table-header">
          <div className="table-header-title">{messages("common.total", {total: pagination.total ? pagination.total : '0'})}</div>
          {/* 共搜索到total条数据 */}
          <div className="table-header-buttons">
            <SelectDepOrPerson
              multiple={true}
              title={messages('report-distribution.key22'/*按组织添加员工*/)}
              buttonType={"primary"}
              onlyPerson={true}
              onConfirm={this.addStaffsByOrg}
            />
            <SelectByBtn
              type={'add_employee'}
              title={messages('report-distribution.key23'/*按条件添加员工*/)}
              labelKey={'fullName'}
              buttonType={"primary"}
              valueKey={'userOID'}
              onConfirm={this.addStaffsByCon}
            />
          </div>
        </div>
        <ResizeTable
          columns={columns}
          dataSource={data}
          pagination={pagination}
          loading={loading}
          bordered
          className="clear"
        />
      </div>
    )
  }
  render() {
    const { reportDetail:{copyName,status,copyComments,dataArea,isPublic},isNew,dataAreaOptions} = this.state;
    const { newCopyReportDetail:{name,comments}} = this.state;
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: { span: 6, offset: 1 },
      wrapperCol: { span: 14, offset: 1 }
    };
    return(
      <Form onSubmit={this.updateCopyReport} className="report-distribution">
        <FormItem
          {...formItemLayout}
          label={messages('report-distribution.key24'/*报表副本名称*/)}
        >
          {getFieldDecorator('copyName', {
            rules:
              [{
                required: true,
                message: messages("common.please.enter")
              }],
            initialValue: isNew ? name : (copyName || '')
          })(
            <Input />
          )}
        </FormItem>
        <FormItem
          {...formItemLayout}
          label={messages('report-distribution.key25'/*说明*/)}
        >
          {getFieldDecorator('copyComments', {
            rules:
              [{
                message: messages("common.please.enter")
              },{
                validator: (item,value,callback)=>{
                  if(value.length >100){
                    callback(messages('report-distribution.key26'/*最多输入100个字符*/))
                  }
                  callback();
                }
              }],
            initialValue: isNew ? comments : (copyComments || '')
          })(
            <Input />
          )}
        </FormItem>
        <FormItem
          {...formItemLayout}
          label={messages("common.column.status")}
        >
          {getFieldDecorator('status', {
            rules:
              [{
                required: true,
                message: messages("common.please.enter")
              }],
            initialValue: isNew ? true : (status === "open")
          })(
            <Switch checkedChildren={<Icon type="check" />}
                    unCheckedChildren={<Icon type="cross" />}
                    checked={ this.props.form.getFieldValue('status')}
                    onChange={this.handleChange}
            />
          )}<span className={"report-distribution-switch-span"}>{ this.props.form.getFieldValue('status') ? messages('report-distribution.key10'/*启用*/) : messages('report-distribution.key11'/*未启用*/)}</span>
        </FormItem>
        <FormItem
          {...formItemLayout}
          label={messages('report-distribution.key27'/*可见数据范围*/)}
        >
          {getFieldDecorator('dataArea', {
            rules: [{
              required: true,
              message: messages("common.please.enter")
            }],
            initialValue: isNew ? "1": dataArea
          })(
            <Select placeholder={messages('common.please.select')} >
              {dataAreaOptions.map(option => {
                return <Option key={option.code} value={option.code}>{option.value}</Option>
              })}
            </Select>
          )}
          { this.renderDataArea() }
        </FormItem>
        <FormItem
          {...formItemLayout}
          label={messages('report-distribution.key28'/*报表可见人员*/)}
        >
          {getFieldDecorator('isPublic', {
            rules:
              [{
                required: true,
                message: messages("common.please.enter")
              }],
            initialValue: isNew ? true : (isPublic === "Y")
          })(
            <Switch checkedChildren={<Icon type="check" />}
                    unCheckedChildren={<Icon type="cross" />}
                    checked={this.props.form.getFieldValue('isPublic')}
            />
          )}<span className={"report-distribution-switch-span"}>{ messages('report-distribution.key29'/*全员可见*/) }</span>
        </FormItem>
        {/*报表可见人员 是否全员可见 视图层变化*/}
        { this.props.form.getFieldValue('isPublic') ? this.renderFullVisible() : this.renderNonFullVisible() }  {/*//所在分配人员列表*/}
        <div className="slide-footer">
          <Button type="primary" htmlType="submit" loading={this.state.loading}>{messages("common.save")}</Button>
          <Button onClick={this.onCancel}>{messages("common.cancel")}</Button>
        </div>
      </Form>
    );
  }
}



function mapStateToProps(state) {
  return {
    language : state.login.user.language,
  }
}

const ReportDistributionMaintainForm = Form.create()(ReportDistributionMaintain);

export default connect(mapStateToProps)(ReportDistributionMaintainForm);

